import {
	pub,
	sub
} from '@/common/event.js'
import store from '../index.js'
import moment from 'moment'
import {
	getRqst
} from '../../common/request'
export default {
	namespaced: true,
	state: {
		list: [],
		glist: []
	},
	mutations: {
		cleardata: (state, payload) => {
			state.list = []
			state.glist = []
		},
		setList: (state, payload) => {
			state.list = payload
		},
		addgapply: (state, payload) => {
			state.glist.unshift(payload)
		},
		editgapply: (state, payload) => {
			for(let o of state.glist){
				if(o.id == payload.id){
					o.status = payload.status
					break
				}
			}
		},
		setgList: (state, payload) => {
			state.glist = payload
		},
		setApplyStatus: (state, payload) => {
			for (let o of state.list) {
				if (o.id == payload['key']) {
					o.status = payload['data']
				}
			}
		},
		addApply: (state, payload) => {
			state.list.push(payload)
		},
	},
	actions: {
		async init({
			commit,
			state
		}, {
			payload
		}) {
			const user = uni.getStorageSync("user")
			const ret = await getRqst().post(`bgyx/bgyx/getdata/userapply`, {
				where: [{
					fromid: user.id
				}, {
					toid: user.id
				}],
				order:{
					time:"desc"
				}
			})
			commit(`setList`, ret.data)

			const retg = await getRqst().get(`friend/friend/getguserapply`)
			commit(`setgList`, retg.data)
		}
	},
	init: async function() {
		console.log("apply初始化")
		const user = uni.getStorageSync("user")
		if (user && user.id) {
			store.dispatch({
				type: "apply/init",
				payload: {}
			})
		}

		sub("loginSuccess", () => {
			store.dispatch({
				type: "apply/init",
				payload: {}
			})
		})
		
		sub("logout", function(e) {
			store.commit(`apply/cleardata`, {})
		})

		sub("socket_touser_passapply", (data) => {
			store.commit(`apply/setApplyStatus`, {
				key: data.item.id,
				data: "已通过"
			})
		})

		sub("socket_touser_refuseapply", (data) => {
			store.commit(`apply/setApplyStatus`, {
				key: data.item.id,
				data: "已拒绝"
			})
		})

		sub("socket_touser_friendapply", () => {
			store.dispatch({
				type: "apply/init",
				payload: {}
			})
		})
		
		sub("relink", () => {
			store.dispatch({
				type: "apply/init",
				payload: {}
			})
		})
		
		sub("socket_togroup_gapply", (e) => {
			store.commit(`apply/addgapply`, e)
		})
		
		sub("socket_togroup_groupapplychange", (e) => {
			store.commit(`apply/editgapply`, e)
		})
		
		sub("socket_touser_groupapplychange", (e) => {
			store.commit(`apply/editgapply`, e)
		})
		
		

	}
}